# -*- coding: utf-8 -*-
from django.shortcuts import render

# add by hcq
from django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from app_accounts.models import *
from app_TuringClass.models import *
from django.core.exceptions import *
#send e-mail
from django.core.mail import send_mail
# 调用自行编写的lib库
from app_TuringClass.lib_appTuringClass import *

from django.utils import timezone
import string
import re
import os
import json
import time
import datetime
# Create your views here.

# Add a patterns so that we can directly open the html pages without the prefix TuringClass/
# author: Xiangyi
# date: 2016/11/15
# delete by houchaoqun 2016 11 18
# def Home_TuringClass(request,page_name="Home_TuringClass"):
# 	return render(request, page_name+'Home_TuringClass.html')

# Add an empty function for HomePage
# author: houchaoqun
# date: 2016/11/20
# @csrf_exempt is for "form"

# @csrf_exempt
# def Home_TuringClass(request):
# 	context = {}
# 	context['sum_test'] = test(request, 10, 20)
# 	return render(request, 'Home_TuringClass.html', context)
'''
@csrf_exempt
def Home_TuringClass(request):

	# update QuestionList
	# _QuestionDetails = QuestionDetails.objects.all()
	# for item in _QuestionDetails:
	# 	if item.QuestionStatus == 'Approved':
	# 		if QuestionList.objects.filter(QuestionID = item.QuestionID).exists():
	# 			pass
	# 		else:
	# 			QuestionList(QuestionID = item.QuestionID, QuestionAbstract = item.QuestionAbstract, QuestionContent = item.QuestionContent).save()
	# 			print "[QuestionID] = ",item.QuestionID
	# 			print "QuestionDetails to QuestionList successful..."
	#
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True
	context['Home_active'] = True
	questionSet = QuestionList.objects.all()
	context["questionSet"] = questionSet
	return render(request, 'Home_TuringClass_bound.html', context)
'''
# Add an empty function for Login
# author: houchaoqun
# date: 2016/11/20
# @csrf_exempt
# def Login(request):
# 	context = {}
# 	context['Login_active'] = True
# 	return render(request, 'Login.html', context)

# @csrf_exempt
# def Regist(request):
# 	context = {}
# 	return render(request, 'Regist.html', context)

# Add an empty function for Tags
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def Tags(request):
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True
	tags=QuestionTag.objects.all()
	uls=[]
	for i in range(0,(len(tags)-1)/3+1):
		ul=[]
		j=0
		while i*3+j<len(tags) and j<3:
			ul.append(tags[i*3+j].TagName)
			j+=1
		uls.append(ul)
	context['uls']=uls
	context['QuestionTag_active'] = True
	return render(request, 'Tags.html', context)

# Add an empty function for Help
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def HelpContent(request):
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True

	context['Help_active'] = True
	return render(request, 'HelpContent.html', context)

# Add an empty function for DownloadArea
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def DownloadArea(request):
	if not request.session.has_key("UserID"):
		return HttpResponseRedirect("/Accounts/login/")
		# return HttpResponse('请先登录，再进行下载!')
	List = UploadingFiles.objects.all()
	UserID = request.session.get("UserID")
	user = TuringUser.objects.get(UserID=UserID)
	role = TuringRoleType.objects.get(RoleTypeID=user.RoleTypeID)
	if role.SuperPermission:
		SuperPermission = 1
	else:
		SuperPermission = 0
	context = {}
	context['Login'] = True
	context['DownLoadArea_active'] = True
	context['fileList'] = List
	context['super'] = SuperPermission
	# context = {'fileList':List,'super':SuperPermission}
	return render(request, 'DownloadArea.html', context)


# Add an empty function for Question
# author: houchaoqun
# date: 2016/11/20
@csrf_exempt
def Question(request):
	context = {}
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
		# return HttpResponse('请先登录，再进行提问!')
	else:
		context['Login'] = True
	tags=QuestionTag.objects.all()
	uls=[]
	for i in range(0,(len(tags)-1)/8+1):
		ul=[]
		j=0
		while i*8+j<len(tags) and j<8:
			ul.append(tags[i*8+j].TagName)
			j+=1
		uls.append(ul)
	context['uls']=uls

	context['Question_active'] = True
	return render(request, 'Question.html', context)

'''
@csrf_exempt
def AskSubmit(request):
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True
	if request.method == "POST":
		# void_pattern = re.compile(r'^(\s)*|((<p>((\s)*)</p>))$')
		QuestionAbstract = request.REQUEST.get('title')
		QuestionContent = request.REQUEST.get('post-text')
		# match_abstract=void_pattern.match(QuestionAbstract)
		# match_content=void_pattern.match(QuestionContent)
		# if match_content or match_abstract:
		# 	return HttpResponse("问题标题和问题详情均不能为空！")
		print "QuestionAbstract = ",QuestionAbstract
		_QuestionID = str(len(QuestionDetails.objects.all())+1)
		_QuestionAbstract = request.REQUEST.get('title')
		_QuestionContent = request.REQUEST.get('post-text')
		QuestionDetails(QuestionID = _QuestionID, QuestionAbstract = _QuestionAbstract, QuestionContent = _QuestionContent, QuestionStatus='Approved').save()

		_QuestionListID = str(len(QuestionList.objects.all())+1)
		QuestionList(QuestionID = _QuestionListID, QuestionAbstract = _QuestionAbstract, QuestionContent = _QuestionContent).save()
		questionSet = QuestionList.objects.all()
		context['questionSet'] = questionSet
		context['Home_active'] = True
		return render(request, 'Home_TuringClass_bound.html', context)
	return HttpResponse("Submit failure!")'''

'''
# Usiung GET request to pass the questionID to the server and query it in the database, then return it and show it on the page
# author: Xiangyi
# date: 2016/11/24
@csrf_exempt
def QuestionDetails_View(request):
	if request.method == "GET":
		# select Question where QuestionID=id
		id=request.REQUEST.get('id')
		try:
			# the name of the model has the same name as this view function, this is ugly and I modified it.
			qstn=QuestionDetails.objects.get(QuestionID=string.atoi(id))
		except QuestionDetails.DoesNotExist,e:
			return HttpResponse(str(e)+"</br>Specified question doesn't exist!")
		else:
			context = {"title":qstn.QuestionAbstract,"content":qstn.QuestionContent,"checkerID":qstn.CheckerID}
			return render(request, 'QuestionDetails.html', context)
		finally:
			pass
'''

@csrf_exempt
def Home_TuringClass(request):
	context = {}
	if request.session.has_key('UserID'):
		context['Login'] = True
	context['Home_active'] = True
	questionList = QuestionList.objects.all().order_by('-LastModifyDate')
	questionSet=[]
	for question in questionList:
		q={}
		tags=question.TagsID.split(";")
		tagsName=[]
		if len(tags[0])!=0:
			for tag in tags:
				t=QuestionTag.objects.get(TagID=tag)
				tagsName.append(t.TagName)
		q['tags']=tagsName
		q['BrowseNum']=question.BrowseNum
		q['PraiseNum']=question.PraiseNum
		q['AnswerNum']=question.AnswerNum
		q['QuestionAbstract']=question.QuestionAbstract
		q['QuestionID']=question.QuestionID
		q['AskDate']=timeDelta(question.QuestionCreateDate)
		questionSet.append(q)
	context["questionSet"] = questionSet
	return render(request, 'Home_TuringClass.html', context)
#Use send_mail('subject','message','fromname<from-mail>',['<to-mail>'],fail_silently = False) to send e-mail when needed.
@csrf_exempt
def AskSubmit(request):
	context = {}
	if not request.session.has_key('UserID'):
		return HttpResponse('请先登录，再进行提问')
	context['Question_active'] = True
	if request.method == "POST":
		UserID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=UserID)
		QuestionAbstract = request.POST.get('title')
		QuestionContent = request.POST.get('post-text')
		tags=request.POST.get('tags').split(', ')
		tagID=[]
		if tags[0]!="":
			for tag in tags:
				# t=QuestionTag.objects.get(TagName=tag)
				if QuestionTag.objects.filter(TagName = tag).exists():
					t = QuestionTag.objects.get(TagName=tag)
					tagID.append(t.TagID)
		TagID=";".join(tagID)
		#QD_QuestionID = str(len(QuestionDetails.objects.all())+1)
		QD_QuestionID = str(int(QuestionDetails.objects.raw('SELECT * FROM app_TuringClass_questiondetails ORDER BY QuestionID DESC LIMIT 1')[0].QuestionID)+1)
		focus=UserID

		QuestionDetails(TagsID=TagID, QuizzerID=UserID, QuestionID = QD_QuestionID, QuestionAbstract = QuestionAbstract, QuestionContent = QuestionContent, QuestionStatus='Approved').save()
		QuestionList(LastModifyDate=timezone.now(),FocusByUserID=focus,TagsID=TagID,QuizzerName=user.NickName, QuizzerID=UserID,QuestionID =QD_QuestionID, QuestionAbstract = QuestionAbstract, QuestionContent = QuestionContent).save()
		try:
			send_mail('Attention: There is a new question!!!','Question:\n [ ' + QuestionAbstract + ' ] has been asked. Please Check it as soon as fast.\n  http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID, 'TuringClass<13276022792@sina.cn>', [ '<3345947441@qq.com>'], fail_silently = False)
			# send_mail('Attention: There is a new question!!!','Question:\n [ ' + QuestionAbstract +' ] has been asked. Please Check it as soon as fast. [' + UserID + '] \n  http://115.28.31.19:8090/QuestionDetails/?id=' + str(QD_QuestionID), 'TuringClass<13276022792@sina.cn>', [ '<3345947441@qq.com>'], fail_silently = False)
			# send_mail('[志愿者请注意]: 图灵课程线上系统有个新问题等待您去解决!!!','\n 问题[ ' + QuestionAbstract +' ]已被提问. 请尽快前往解答.\n  http://127.0.0.1:8000/QuestionDetails/?id='+str(QD_QuestionID),'TuringClass<13276022792@sina.cn>', [ '<3345947441@qq.com>'], fail_silently = False)
			# try:
			# 	fo_Success = open(".\\app_TuringClass\Email_Success.log", "wb")
			# 	EmailContent = '[ ' + QuestionAbstract + ' ] has been asked. Link = http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID + '\n'
			# 	fo_Success.write(EmailContent)
			# except IOError:
			# 	print "Error: 没有找到文件或读取文件失败"
   			# else:
   			# 	fo_Success.close()
		except:
			print "[Failure] send_mail() - [ ", QuestionAbstract , "]"
			try:
				fo_Failure = open(".\\app_TuringClass\Email_Failure.log", "a")
				# write, 如果文件存在，则会首先清空，然后写入, 设置文件打开的方式为'a'，表示将打开追加文件。文件指针是在文件的结尾。也就是说，该文件是在附加模式。如果该文件不存在，它创造了写入一个新的文件
				# EmailContent = '[Failuer] - ( ' + QuestionAbstract + ' ) has been asked. Link = http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID + '\n'
				fo_Failure.writelines('[Failure] - ( ' + QuestionAbstract + ' ) has been asked. Link = http://127.0.0.1:8000/QuestionDetails/?id=' + QD_QuestionID + '\n')
			except IOError:
				print "Error: 没有找到文件或读取文件失败"
    		else:
    			fo_Failure.close()
		finally:
			return HttpResponseRedirect('/')
	return HttpResponse("Whoops!")

def timeDelta(dateTime):
	time=dateTime.replace(tzinfo=None)
	delta=datetime.datetime.utcnow()-time
	if delta.days>0:
		if delta.days==1:
			timedelta=str(delta.days)+" day ago"
		else:
			timedelta=str(delta.days)+" days ago"
	else:
		if delta.seconds>3600:
			if delta.seconds<7200:
				timedelta="1 hour ago"
			else:
				timedelta=str(delta.seconds/3600)+" hours ago"
		else:
			if delta.seconds>60:
				if delta.seconds<120:
					timedelta="1 minute ago"
				else:
					timedelta=str(delta.seconds/60)+" minutes ago"
			else:
				if delta.seconds<=1:
					timedelta="1 second ago"
				else:
					timedelta=str(delta.seconds)+" seconds ago"
	return timedelta

def showQuestionDetail(request, ID):
	detail=QuestionList.objects.filter(QuestionID=ID)[0]
	timedelta=timeDelta(detail.QuestionCreateDate)
	if not detail:
		return HttpResponse("Whoops!")
	else:
		detail.BrowseNum+=1
		detail.save()
		answers=QuestionAnswers.objects.filter(QuestionID=ID).order_by("-PraiseNum")
		Answers=[]
		for answer in answers:
			Answer={}
			Answer['ResponderName']=answer.ResponderName
			Answer['AnswerContent']=answer.AnswerContent
			Answer['PraiseNum']=answer.PraiseNum
			Answer['OpposeNum']=answer.OpposeNum
			Answer['answerTime']=timeDelta(answer.AnswerDate)
			Answer['AnswerID']=answer.AnswerID
			Answers.append(Answer)
		tagName=[]
		if len(detail.TagsID)!=0:
			tags=detail.TagsID.split(";")
			for tag in tags:
				name=QuestionTag.objects.get(TagID=tag).TagName
				tagName.append(name)
		context={
			'questionTime':timedelta,
			'question':detail,
			'answers':Answers,
			'tags':tagName,
			}
		if request.session.has_key('UserID'):
			context['Login'] = True
		return context

@csrf_exempt
def AnswerSubmit(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
	if request.method=="POST":
		Content = request.POST.get('post-text')
		questionID=request.POST.get('qID')
		respondentID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=respondentID)
		respondentName=user.NickName
		answerID=time.strftime("%Y%m%d_%H%M%S", time.gmtime())
		try:
			question=QuestionList.objects.get(QuestionID=questionID)
		except:
			return HttpResponse('Whoops!')
		else:
			QuestionAnswers(
				AnswerContent=Content,
				QuestionID=questionID,
				AnswerID=answerID,
				ResponderID=respondentID,
				ResponderName=respondentName,).save()
			question.AnswerNum+=1;
			question.LastModifyDate=timezone.now()
			flag=0
			if question.FocusByUserID:
				List=question.FocusByUserID.split(";")
				for l in List:
					if user.UserID==l:
						flag=1
			else:
				List=[]
			if flag==0 and request.POST.has_key('receive_email'):
				List.append(user.UserID)
				f=";".join(List)
				question.FocusByUserID=f
				if user.QuestionString:
					qList=user.QuestionString.split(";")
				else:
					qList=[]
				qList.append(questionID)
				q=";".join(qList)
				user.QuestionString=q
				user.save()
			question.save()
			for l in List:
				if user.UserID!=l:
					u=TuringUser.objects.get(UserID=l)
					#send_mail('TuringClass: New answer for the Question!!!','Question:\n [ ' + question.QuestionAbstract +' ] has been replied. \n  http://127.0.0.1:8000/QuestionDetails/?id='+questionID,'TuringClass<'+u.UserEmail+'>', [ '<3345947441@qq.com>'], fail_silently = False)
			return HttpResponseRedirect('/QuestionDetails/?id='+questionID)

@csrf_exempt
def QuestionDetailsView(request):
	if request.method=="GET":
		ID=str(request.GET.get('id'))
		context=showQuestionDetail(request, ID)
		if request.session.has_key('UserID'):
			user=TuringUser.objects.get(UserID=request.session.get('UserID'))
			if user.QuestionString:
				qstring=user.QuestionString.split(";")
				for s in qstring:
					if s==ID:
						context['Liked']=True
		return render(request,'QuestionDetails.html',context)

def GetFileNameAndExt(filename):
	(filepath,tempfilename) = os.path.split(filename);
	(shotname,extension) = os.path.splitext(tempfilename);
	return shotname,extension

def saveFile(file,UserID):
	user=TuringUser.objects.get(UserID=UserID)
	role=TuringRoleType.objects.get(RoleTypeID=user.RoleTypeID)
	if not role.SuperPermission:
		return "Action denied!"
	filename,filetype=GetFileNameAndExt(file.name)
	file.name=filename + "_" + time.strftime("%Y%m%d_%H%M%S", time.gmtime()) + '_' + user.NickName + filetype
	File=UploadingFiles.objects.filter(FileName=file.name)
	if not File:
		UploadingFiles(FileName=file.name).save()
	else:
		i=1
		File=UploadingFiles.objects.filter(FileName="dif"+"_"+str(i)+"_"+file.name)
		while File:
			i+=1
			File=UploadingFiles.objects.filter(FileName="dif"+"_"+str(i)+"_"+file.name)
		file.name="dif"+"_"+str(i)+"_"+file.name
		UploadingFiles(FileName=file.name,UploaderID=UserID,UploaderName=user.NickName).save()
	destination = open("./app_TuringClass/Documents_Upload/"+file.name,'wb+')
	for chunk in file.chunks():
		destination.write(chunk)
	destination.close()
	return "Upload over"

@csrf_exempt
def Upload(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method == "POST":
		UserID=request.session.get('UserID')
		myFile =request.FILES.getlist("Filedata", None)
		if not myFile:
			return HttpResponse("no files for upload!")
		for file in myFile:
			info=saveFile(file,UserID)
		return HttpResponse(info)

@csrf_exempt
def DeleteFile(request):
	dic = {'info':'ok'}
	if request.method == 'POST':
		path=request.POST.get('file')
		UploadingFiles.objects.filter(FileName=path).delete()
        target=os.path.join('./app_TuringClass/Documents_Upload/',path)
        os.remove(target)
        data=json.dumps(dic)
        return HttpResponse(data)

def DownloadFile(request):
    filename_=request.GET.get('file')
    filepath_=os.path.join("./app_TuringClass/Documents_Upload/",filename_)
    def readFile(fn, buf_size=262144):
        f = open(fn, "rb")
        while True:
            c = f.read(buf_size)
            if c:
                yield c
            else:
                break
        f.close()
    file=UploadingFiles.objects.get(FileName=filename_)
    file.DownloadNum+=1
    file.save()
    response = StreamingHttpResponse(readFile(filepath_), content_type='APPLICATION/OCTET-STREAM')
    response['Content-Disposition'] = 'attachment; filename='+filename_.encode('utf-8')
    response['Content-Length'] = os.path.getsize(filepath_)
    return response

def QuestionPraise(request):
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		question=QuestionList.objects.get(QuestionID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if question.SupportByUserID:
			praisers=question.SupportByUserID.split(";")
			for praiser in praisers:
				if userID==praiser:
					dic={'info':str(question.PraiseNum)}
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			praisers=[]
		praisers.append(userID)
		p=";".join(praisers)
		question.SupportByUserID=p
		question.PraiseNum+=1
		question.save()
		dic={'info':str(question.PraiseNum)}
		data=json.dumps(dic)
        return HttpResponse(data)

def QuestionOppose(request):
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		question=QuestionList.objects.get(QuestionID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if question.NonSupportByUserID:
			opposers=question.NonSupportByUserID.split(";")
			for opposer in opposers:
				if userID==opposer:
					dic={'info':str(question.OpposeNum)}
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			opposers=[]
		opposers.append(userID)
		o=";".join(opposers)
		question.NonSupportByUserID=o
		question.OpposeNum+=1
		question.save()
		dic={'info':str(question.OpposeNum)}
		data=json.dumps(dic)
        return HttpResponse(data)

def AnswerPraise(request):
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		answer=QuestionAnswers.objects.get(AnswerID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if answer.SupportByUserID:
			praisers=answer.SupportByUserID.split(";")
			for praiser in praisers:
				if userID==praiser:
					dic={'info':str(answer.PraiseNum)}
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			praisers=[]
		praisers.append(userID)
		p=";".join(praisers)
		answer.SupportByUserID=p
		answer.PraiseNum+=1
		answer.save()
		dic={'info':str(answer.PraiseNum)}
		data=json.dumps(dic)
        return HttpResponse(data)

def AnswerOppose(request):
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	ID=request.GET.get('id')
	try:
		answer=QuestionAnswers.objects.get(AnswerID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if answer.NonSupportByUserID:
			opposers=answer.NonSupportByUserID.split(";")
			for opposer in opposers:
				if userID==opposer:
					dic={'info':str(answer.OpposeNum)}
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			opposers=[]
		opposers.append(userID)
		o=";".join(opposers)
		answer.NonSupportByUserID=o
		answer.OpposeNum+=1
		answer.save()
		dic={'info':str(answer.OpposeNum)}
		data=json.dumps(dic)
        return HttpResponse(data)

def like_it(request):
	if not request.session.has_key('UserID'):
		dic={'info':'please login first!'}
		data=json.dumps(dic)
		return HttpResponse(data)
	userID=request.session.get('UserID')
	user=TuringUser.objects.get(UserID=userID)
	ID=request.GET.get('id')
	try:
		question=QuestionList.objects.get(QuestionID=ID)
	except:
		dic={'info':'failed'}
		data=json.dumps(dic)
		return HttpResponse(data)
	else:
		if question.FocusByUserID:
			List=question.FocusByUserID.split(";")
			for l in List:
				if userID==l:
					List.remove(userID)
					f=";".join(List)
					question.FocusByUserID=f
					question.save()
					qList=user.QuestionString.split(";")
					qList.remove(ID)
					q=";".join(qList)
					user.QuestionString=q
					user.save()
					dic={'info':"disliked"}
					data=json.dumps(dic)
					return HttpResponse(data)
		else:
			List=[]
		List.append(userID)
		f=";".join(List)
		question.FocusByUserID=f
		question.save()
		if user.QuestionString:
			qList=user.QuestionString.split(";")
		else:
			qList=[]
		qList.append(ID)
		q=";".join(qList)
		user.QuestionString=q
		user.save()
		dic={'info':"liked"}
		data=json.dumps(dic)
		return HttpResponse(data)

def PersonalInfo(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect("/Accounts/login/")
		#return HttpResponse('请先登录！')
	UserID=request.session.get('UserID')
	q=QuestionList.objects.filter(QuizzerID=UserID)
	a=QuestionAnswers.objects.filter(ResponderID=UserID)
	questionNum=len(q)
	answerNum=len(a)
	praiseNum=0
	for _q in q:
		praiseNum+=_q.PraiseNum
	for _a in a:
		praiseNum+=_a.PraiseNum
	user=TuringUser.objects.get(UserID=UserID)
	lastLogin=user.LastLoginTime
	if user.QuestionString:
		questionString=user.QuestionString.split(";")
	else:
		questionString=[]
	List=[]
	gather={}
	for questionID in questionString:
		question=QuestionList.objects.get(QuestionID=questionID)
		abstract=question.QuestionAbstract
		gather['questionID']=question.QuestionID
		gather['questionAbstract']=abstract
		answers=QuestionAnswers.objects.filter(QuestionID=questionID,AnswerDate__gt=lastLogin).order_by('-AnswerDate')#raw("select * from app_turingclass_questionanswers where QuestionID=questionID ")
		for answer in answers:
			if answer.ResponderID != UserID:
				gather['date']=answer.AnswerDate
				List.append(gather)
				break
	List.sort(key=lambda x:x['date'],reverse=True)
	context = {'praiseNum':praiseNum,'questionNum':questionNum,'answerNum':answerNum,'list':List,'user':user}
	context['Login'] = True
	context['Personal_active'] = True
	return render(request,'PersonalInfo.html', context)

'''
@csrf_exempt
def ModifyEmail(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		email=request.POST.get('email')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.UserEmail=email
		user.save()
		context={'email':email}
		data=json.dumps(context)
		return HttpResponse(data)
	return HttpResponse('Whoops!')
'''

@csrf_exempt
def ModifyQQ(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		qq=request.POST.get('qq')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.UserQQ=qq
		user.save()
		context={'qq':qq}
		data=json.dumps(context)
		return HttpResponse(data)
	return HttpResponse('Whoops!')

@csrf_exempt
def ModifyTelephone(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method=="POST":
		telephone=request.POST.get('telephone')
		userID=request.session.get('UserID')
		user=TuringUser.objects.get(UserID=userID)
		user.MobilePhone=telephone
		user.save()
		context={'telephone':telephone}
		data=json.dumps(context)
		return HttpResponse(data)
	return HttpResponse('Whoops!')

@csrf_exempt
def UploadIMG(request):
	if not request.session.has_key('UserID'):
		return HttpResponseRedirect('/Accounts/login/')
	if request.method == 'POST':
		callback = request.GET.get('CKEditorFuncNum')
		try:
			path = "static/upload/"
			f = request.FILES["upload"]
			n,e=GetFileNameAndExt(f.name)
			file_name = path+request.session.get('UserID')+"_"+time.strftime("%Y%m%d_%H%M%S", time.gmtime())+e
			des_origin_f = open(file_name, "wb+")
			for chunk in f.chunks():
				des_origin_f.write(chunk)
			des_origin_f.close()
		except Exception, e:
			print e
		res = "<script>window.parent.CKEDITOR.tools.callFunction("+callback+",'/"+file_name+"', '');</script>"
		return HttpResponse(res)
	else:
		raise Http404()
